//
//  AppDelegate.m
//  JingleSpeedLoan
//
//  Created by 宋质彬 on 2018/6/19.
//  Copyright © 2018年 宋质彬. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "DSNetWorkStatus.h"
#import "JSLTabBarController.h"
#import "AppConfig.h"
#import "LaunchViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
   

    //  配置视图
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    ViewController *viewController = [[ViewController alloc] init];
    
    self.window.rootViewController = viewController;
    
    
    [self.window makeKeyAndVisible];
    
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self gotoTabbarController];
//    });
    
    
     //判断网络状态x
    [HttpRequest judgeNetworkStatusWithSuccess:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
            [self tipWarnAddContacts];
        }
    }];
    
    
    [DSNetWorkStatus sharedNetWorkStatus];
//
//
    [self configAppInterface];
//
//    // 获取用户信息
    [self configUserInfo];
    
    
    return YES;
}

- (void)setUMAnalyze {
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick setLogEnabled:YES];
    UMConfigInstance.appKey = @"";
    UMConfigInstance.channelId = @"";
    [MobClick startWithConfigure:UMConfigInstance];
    //    [self getUMAnalyze_testDevice];
    
}

- (void)configInitData {
    NSMutableArray *arrm = [NSMutableArray arrayWithArray:@[@{
                                                                @"name":@"买健身器材",
                                                                
                                                                },@{
                                                                @"name":@"买电子设备",
                                                                
                                                                }]];
    [CacheManager setObject:arrm forKey:@"JSL_BILL_PRODUCT"];
    
}

- (void)configAppInterface {
    NSDictionary*infoDictionary=[[NSBundle mainBundle] infoDictionary];
    NSString*app_Version=[infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *version= [NSString stringWithFormat:@"%@",app_Version];
    NSMutableDictionary *paramters = [[NSMutableDictionary alloc] init];
    paramters[@"version"] = version;
    paramters[@"clientType"] = @"2";
    paramters[@"packageName"] = @"叮当账单";
    paramters[@"channelName"] = @"AppStore";
    
    [HttpRequest POST:APP_CONFIG_URL parameters:paramters success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        
        NSDictionary *info = (NSDictionary *)result;
        
        if ([info[@"data"] boolValue]) {
            [AppConfig shareConfig].audit = YES;
        }else {
            [AppConfig shareConfig].audit = NO;
        }
        
        if ([AppConfig shareConfig].audit) {
           // 使用壳
            [self gotoTabbarController];
            
        }else {
            
            
            // 不使用壳
            // 使用NSUserDefaults判断程序是否第一次启动(其他方法也可以)
            if (![[NSUserDefaults standardUserDefaults] boolForKey:BOO_FIRST_SAVE]) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BOO_FIRST_SAVE];
                // 在这里写初始化图片数组和DHGuidePageHUD库引导页的代码
                
                if( IS_IPHONE ){
                    // iphone处理
                    [self configInitData];
                    
                    [self gotoLaunchViewControoler:YES];
                }else{
                    [self gotoTabbarController];
                }
                
            }else {
                [self gotoTabbarController];
            }
        }
        
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        [AppConfig shareConfig].audit = YES;
        [self gotoTabbarController];
    } errors:^(NSError * _Nonnull error) {
       
        
        // 不使用壳
        // 使用NSUserDefaults判断程序是否第一次启动(其他方法也可以)
        if (![[NSUserDefaults standardUserDefaults] boolForKey:BOO_FIRST_SAVE]) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BOO_FIRST_SAVE];
            // 在这里写初始化图片数组和DHGuidePageHUD库引导页的代码
            
            [self configInitData];
            [AppConfig shareConfig].audit = YES;
            [self gotoTabbarController];
        }else {
            [AppConfig shareConfig].audit = YES;
            [self gotoTabbarController];
        }
    }];
    
    
}

- (void)configUserInfo{
#pragma mark - 获取用户信息

        // 设置token
        NSString *userToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
        parameters[@"userPhone"] = userToken;
        
        [HttpRequest POST:USERINFO_URL parameters:parameters success:^(id  _Nullable result, NSString * _Nullable successMessage) {
            
            NSLog(@"%@",result);
            NSDictionary *userDict = result[@"data"];
            
            // 创建用户模型
            UserInfo *userModel =   [UserInfo yy_modelWithJSON:userDict.yy_modelToJSONString];
            // 创建用户模型管理者
            [UserManager manager].userInfo = userModel;
            
            
             [MobClick event:@"launch" attributes:@{@"Launch_login":@"登录启动"}];
        
        } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
            // 清空用户模型
            UserInfo *userModel = [UserInfo yy_modelWithJSON:@""];
            [UserManager manager].userInfo = userModel;
            [UserManager  logout];
            NSLog(@"%@",errorMessage);
            
             [MobClick event:@"launch" attributes:@{@"Launch_noLogin":@"未登录启动"}];
            
        }];
        
    
}



#pragma mark -
- (void)tipWarnAddContacts {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"网络连接失败，请重新连接网络以取得更好的体验" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertVC addAction:sure];
    
    //展示
    [[JSLKitFactory currentViewController] presentViewController:alertVC animated:YES completion:nil];
}

- (void)gotoLaunchViewControoler:(BOOL)isFirstLunche{
    LaunchViewController *launchVC = [[LaunchViewController alloc] init];
    launchVC.isFirstLunche = isFirstLunche;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:launchVC];
    self.window.rootViewController = nav;
}

- (void)gotoTabbarController {

    
    JSLTabBarController *tabBarVC = [[JSLTabBarController alloc] init];
    
    self.window.rootViewController = tabBarVC;
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
